<template>
	<view class="coupon-center-page">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">领券中心</text>
			<text class="page-subtitle">精选优惠券，先到先得</text>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<view class="loading-skeleton">
				<view v-for="n in 3" :key="n" class="skeleton-card">
					<view class="skeleton-left"></view>
					<view class="skeleton-right">
						<view class="skeleton-line skeleton-title"></view>
						<view class="skeleton-line skeleton-desc"></view>
						<view class="skeleton-line skeleton-time"></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 错误状态 -->
		<view v-else-if="error" class="error-container">
			<view class="error-icon">😵</view>
			<text class="error-text">{{ errorMessage }}</text>
			<button class="retry-btn" @click="loadCouponTemplates">重试</button>
		</view>

		<!-- 空状态 -->
		<view v-else-if="couponTemplates.length === 0" class="empty-container">
			<view class="empty-icon">🎫</view>
			<text class="empty-text">暂无可领取的优惠券</text>
			<text class="empty-subtitle">请关注我们的最新活动</text>
		</view>

		<!-- 优惠券列表 -->
		<view v-else class="coupons-container">
			<view 
				v-for="coupon in couponTemplates" 
				:key="coupon.template_id"
				class="coupon-card"
				:class="getCouponCardClass(coupon)"
			>
				<!-- 优惠券主体 -->
				<view class="coupon-main">
					<!-- 左侧价值区域 -->
					<view class="coupon-value" :class="getValueClass(coupon)">
						<view class="value-container">
							<text v-if="coupon.type === 'fixed'" class="value-number">￥{{ coupon.value }}</text>
							<text v-else class="value-number">{{ getDiscountText(coupon.value) }}</text>
							<text class="value-label">{{ coupon.type === 'fixed' ? '立减' : '折扣' }}</text>
						</view>
					</view>

					<!-- 右侧信息区域 -->
					<view class="coupon-info">
						<view class="coupon-name">{{ coupon.name }}</view>
						<view class="coupon-desc">{{ coupon.description }}</view>
						<view class="coupon-validity">
							<text class="validity-text">{{ coupon.validity_description }}</text>
						</view>
						<!-- 隐藏剩余张数显示
						<view v-if="coupon.remaining_quantity !== null" class="coupon-stock">
							<text class="stock-text">剩余 {{ coupon.remaining_quantity }} 张</text>
						</view>
						-->
					</view>

					<!-- 操作按钮 -->
					<view class="coupon-action">
						<button 
							class="action-btn"
							:class="getButtonClass(coupon)"
							:disabled="!coupon.can_claim || claiming === coupon.template_id"
							@click="handleClaimCoupon(coupon)"
						>
							<text class="btn-text">{{ getButtonText(coupon) }}</text>
						</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 下拉刷新提示 -->
		<view class="refresh-tip">
			<text class="tip-text">下拉刷新获取最新优惠券</text>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import { getAvailableCouponTemplates, claimCoupon } from '../../api/couponCenter.js'

// 响应式数据
const loading = ref(false)
const error = ref(false)
const errorMessage = ref('')
const couponTemplates = ref([])
const claiming = ref(null) // 当前正在领取的优惠券ID

// 页面加载时获取数据
onMounted(() => {
	loadCouponTemplates()
})

// 下拉刷新
onPullDownRefresh(() => {
	loadCouponTemplates().finally(() => {
		uni.stopPullDownRefresh()
	})
})

// 加载优惠券模板数据
const loadCouponTemplates = async () => {
	if (loading.value) return
	
	loading.value = true
	error.value = false
	
	try {
		const response = await getAvailableCouponTemplates()
		
		if (response.success) {
			couponTemplates.value = response.data || []
		} else {
			throw new Error(response.message || '获取数据失败')
		}
		
	} catch (err) {
		console.error('获取优惠券模板失败:', err)
		error.value = true
		errorMessage.value = err.message || '获取优惠券失败，请稍后重试'
	} finally {
		loading.value = false
	}
}

// 领取优惠券
const handleClaimCoupon = async (coupon) => {
	if (!coupon.can_claim || claiming.value === coupon.template_id) {
		return
	}
	
	// 检查登录状态
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showModal({
			title: '提示',
			content: '请先登录后再领取优惠券',
			showCancel: false,
			success: () => {
				uni.switchTab({
					url: '/pages/my/my'
				})
			}
		})
		return
	}
	
	claiming.value = coupon.template_id
	
	try {
		const response = await claimCoupon(coupon.template_id)
		
		if (response.success) {
			// 更新本地状态
			coupon.can_claim = false
			coupon.claim_status = 'already_claimed'
			coupon.is_claimed = true
			
			// 更新剩余数量
			if (coupon.remaining_quantity !== null) {
				coupon.remaining_quantity = Math.max(0, coupon.remaining_quantity - 1)
			}
			
			uni.showToast({
				title: '领取成功！',
				icon: 'success',
				duration: 2000
			})
		} else {
			throw new Error(response.message || '领取失败')
		}
		
	} catch (err) {
		console.error('领取优惠券失败:', err)
		uni.showToast({
			title: err.message || '领取失败，请重试',
			icon: 'none',
			duration: 2000
		})
	} finally {
		claiming.value = null
	}
}

// 获取优惠券卡片样式类
const getCouponCardClass = (coupon) => {
	if (!coupon.can_claim) {
		if (coupon.claim_status === 'already_claimed') {
			return 'coupon-claimed'
		} else if (coupon.claim_status === 'out_of_stock') {
			return 'coupon-unavailable'
		} else {
			return 'coupon-disabled'
		}
	}
	return 'coupon-available'
}

// 获取价值区域样式类
const getValueClass = (coupon) => {
	if (!coupon.can_claim) {
		return 'value-disabled'
	}
	return coupon.type === 'fixed' ? 'value-fixed' : 'value-discount'
}

// 获取按钮样式类
const getButtonClass = (coupon) => {
	if (claiming.value === coupon.template_id) {
		return 'btn-claiming'
	} else if (!coupon.can_claim) {
		return 'btn-disabled'
	}
	return 'btn-available'
}

// 获取按钮文字
const getButtonText = (coupon) => {
	if (claiming.value === coupon.template_id) {
		return '领取中...'
	} else if (coupon.claim_status === 'already_claimed') {
		return '已领取'
	} else if (coupon.claim_status === 'out_of_stock') {
		return '已抢完'
	} else if (!coupon.can_claim) {
		return '不可领取'
	}
	return '立即领取'
}

// 获取折扣文本
const getDiscountText = (value) => {
	return `${value}折`
}
</script>

<style scoped>
.coupon-center-page {
	min-height: 100vh;
	background-color: #f5f5f5;
}

/* 页面标题 */
.page-header {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 40rpx 40rpx 30rpx;
	color: white;
	text-align: center;
}

.page-title {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.page-subtitle {
	display: block;
	font-size: 26rpx;
	opacity: 0.9;
}

/* 加载状态 */
.loading-container {
	padding: 20rpx;
}

.loading-skeleton {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.skeleton-card {
	background: white;
	border-radius: 16rpx;
	padding: 30rpx;
	display: flex;
	align-items: center;
	gap: 30rpx;
}

.skeleton-left {
	width: 120rpx;
	height: 120rpx;
	background: #f0f0f0;
	border-radius: 12rpx;
	animation: skeleton-loading 1.5s ease-in-out infinite;
}

.skeleton-right {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.skeleton-line {
	height: 24rpx;
	background: #f0f0f0;
	border-radius: 12rpx;
	animation: skeleton-loading 1.5s ease-in-out infinite;
}

.skeleton-title {
	width: 60%;
}

.skeleton-desc {
	width: 80%;
}

.skeleton-time {
	width: 40%;
}

@keyframes skeleton-loading {
	0%, 100% {
		opacity: 1;
	}
	50% {
		opacity: 0.6;
	}
}

/* 错误状态 */
.error-container,
.empty-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 40rpx;
	text-align: center;
}

.error-icon,
.empty-icon {
	font-size: 120rpx;
	margin-bottom: 30rpx;
}

.error-text,
.empty-text {
	font-size: 32rpx;
	color: #666;
	margin-bottom: 20rpx;
}

.empty-subtitle {
	font-size: 26rpx;
	color: #999;
}

.retry-btn {
	margin-top: 30rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	border: none;
	border-radius: 50rpx;
	padding: 20rpx 40rpx;
	font-size: 28rpx;
}

/* 优惠券列表 */
.coupons-container {
	padding: 20rpx;
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

/* 优惠券卡片基础样式 */
.coupon-card {
	background: white;
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

.coupon-main {
	display: flex;
	align-items: center;
	position: relative;
}

/* 左侧价值区域 */
.coupon-value {
	width: 160rpx;
	height: 160rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	color: white;
	position: relative;
	flex-shrink: 0;
}

.value-fixed {
	background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
}

.value-discount {
	background: linear-gradient(135deg, #4ecdc4, #44a08d);
}

.value-disabled {
	background: linear-gradient(135deg, #bbb, #ddd);
}

.value-container {
	text-align: center;
}

.value-number {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	line-height: 1;
	margin-bottom: 8rpx;
}

.value-label {
	font-size: 20rpx;
	opacity: 0.9;
}

/* 右侧信息区域 */
.coupon-info {
	flex: 1;
	padding: 30rpx;
	display: flex;
	flex-direction: column;
	gap: 12rpx;
}

.coupon-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.coupon-desc {
	font-size: 26rpx;
	color: #666;
}

.coupon-validity {
	font-size: 24rpx;
	color: #999;
}

.coupon-stock {
	font-size: 22rpx;
	color: #ff6b6b;
}

/* 操作按钮区域 */
.coupon-action {
	padding: 30rpx;
	flex-shrink: 0;
}

.action-btn {
	width: 140rpx;
	height: 60rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
	border: none;
	transition: all 0.3s ease;
}

.btn-available {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
}

.btn-claiming {
	background: #ccc;
	color: white;
}

.btn-disabled {
	background: #f0f0f0;
	color: #999;
}

.btn-text {
	font-size: 24rpx;
}

/* 不同状态的卡片样式 */
.coupon-available {
	border-left: 6rpx solid #667eea;
}

.coupon-claimed {
	opacity: 0.7;
	border-left: 6rpx solid #52c41a;
}

.coupon-unavailable {
	opacity: 0.6;
	border-left: 6rpx solid #ff4d4f;
}

.coupon-disabled {
	opacity: 0.5;
	border-left: 6rpx solid #d9d9d9;
}

/* 刷新提示 */
.refresh-tip {
	text-align: center;
	padding: 40rpx;
}

.tip-text {
	font-size: 24rpx;
	color: #ccc;
}
</style>